package com.misty.blog.controller.authController;

import cn.hutool.core.util.StrUtil;
import com.misty.api.param.email.EmailParam;
import com.misty.api.service.EmailService;
import com.misty.auth.service.AuthService;
import com.misty.blog.service.UsersService;
import com.misty.common.bean.Result;
import com.misty.common.param.LoginParam;
import com.misty.dao.domain.Users;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/")
@Slf4j
public class AuthController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private EmailService emailService;

    @Autowired
    private AuthService authService;

    @PostMapping("login")
    public Result<?> login(@RequestBody LoginParam param){
        return authService.login(param);
    }

    @PostMapping("register")
    public Result<?> register(@RequestBody Users user) {
        return authService.register(user);
    }

    @PutMapping("/changePassword")
    @ApiOperation(value = "修改密码")
    public Result<?> changePassword(@RequestBody Users user) {

        Result<?> result = authService.changePassword(user);
        if (result.isErrorResult()) {
            return result;
        }
        Map<String,Object> map = (HashMap)result.getData();
        Integer userId = (Integer)map.get("userId");
        // 发送邮件
        Users users = usersService.getById(userId);
        /* 暂时方案，后面用mq发邮箱  */
        if(StrUtil.isNotEmpty(users.getEmail())){
            emailService.sendRegisterMail(users.getEmail(),"修改密码","密码修改成功!");
        }
        return Result.success(0,"修改密码成功");
    }


    @PostMapping("user/logout")
    public Result<?> logout() {
        return authService.logout();
    }

    @PostMapping("email")
    public Result<?> email(@RequestBody EmailParam param) {
        // 发送邮件
        emailService.sendRegisterMail( param.getTo(), param.getSubject(), param.getText());
        return Result.success(0,"发送邮箱成功");
    }

    @PostMapping("emailCode")
    public Result<?> emailCode(@RequestBody EmailParam param) {
        // 发送邮件
        try {
            emailService.sendHtmlEmail( param.getTo(), param.getSubject(), param.getText());
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return Result.success(0,"发送邮箱验证码成功");
    }

}
